package net.zjitc.security.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.zjitc.entity.Manger;
import net.zjitc.entity.Role;
import net.zjitc.mapper.RoleMapper;
import net.zjitc.security.auth.MyGrantedAuthority;
import net.zjitc.security.model.ManageUserDetails;
import net.zjitc.service.MangerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证器，从数据库中取数据进行认证
 */
@Service
@Transactional
public class UserDeatilsServiceImpl implements UserDetailsService {
    @Autowired
    private MangerService managerService;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询用户
        Manger manager = managerService.selectByUsername(username);

        //查询当前用户角色（）
        //todo
        //角色放在
        List<MyGrantedAuthority> authorityList = new ArrayList<>();
        //一个用户可以有多个角色，本数据库一个用户只有一个角色
        List<Role> roleList = roleMapper.selectList(Wrappers.<Role>lambdaQuery().eq(Role::getId,manager.getRole_id()));
        //当角色为null或者为0的时候，权限列表为空
        if (roleList==null|| roleList.size()==0){
            authorityList=null;
        }else{
            //从角色列表中拿到角色，并处理角色的权限ids
            for (Role role: roleList) {
                String psIds = role.getPs_ids();
                //如果当前角色的权限ids为空，则不作spilt处理
                if (psIds==null || psIds.length()==0){
                    continue;
                }else {
                    String[] split = psIds.split(",");
                    //将ids数组转成集合
                    List<MyGrantedAuthority> collect = Arrays.asList(split).stream().map(str -> new MyGrantedAuthority(str.toString())).collect(Collectors.toList());
                    authorityList.addAll(collect);
                }
            }
        }
        ManageUserDetails userDetails = new ManageUserDetails(manager.getUsername(), manager.getPassword(), authorityList);
        return userDetails;
    }
}
